<?php
if ( ! defined('ROOT')) exit('No direct script access allowed');

/**
 * 应用程序创建类
 * @author gzute
 * @link http://www.gzute.com
 */

class Application
{
	public $module;
	public $controller;
	public $action;
	
	public function __construct()
	{
		Base::load_sys_class('interfaceApp');
		Base::load_sys_class('db_factory');
		Base::load_sys_class('model');
		$router = Base::load_sys_class('router');
		$this->module = $router->get_module();
		$this->controller = $router->get_controller();
		$this->action = $router->get_action().'Action';
		self::init();
	}
	
	private function init()
	{
		$controller = $this->load_controller();
		if (method_exists($controller, $this->action)) {
			if (preg_match('/^[_]/i', $this->action)) {
				show_error('You are visiting the action is to protect the private action');
			} else {
				call_user_func(array($controller, $this->action));
			}
		} else {
			show_404("{$this->action}");
		}
	}
	
	/**
	 * 加载控制器
	 * @param string $filename
	 * @param string $m
	 * @return obj
	 */
	private function load_controller($filename = '', $m = '') {
		if (empty($filename)) $filename = $this->controller;
		if (empty($m)) $m = $this->module;
		$filepath = LIB_PATH.'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.$filename.'.php';
		if (file_exists($filepath)) {
			$classname = ucfirst($filename);
			include $filepath;
			return new $classname;
		} else {
			show_404("{$this->controller}");
		}
	}
}
